<template>
    <div class="app-container">
        <div class="table-wrapper">
            <h4>桥梁易损性计算</h4>
            <el-form :inline="true" ref="queryRef" :disabled="route.query.operateType&&(route.query.operateType=='query')" :rules="rules" label-position="right" :model="params"
                label-width="320px">
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="桥梁名称：" class="form-item" prop="name">
                            <el-input v-model="params.name" placeholder=""
                                :disabled="disabled && !!route.query.operateType" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="年代：" class="form-item" prop="year">
                            <el-input v-model="params.year" placeholder="请输入" :disabled="disabled" clearable />
                            <!-- <el-select v-model="params.year" placeholder="请选择" class="form-select" :disabled="disabled"
                                clearable>
                                <el-option v-for="item in yearsOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select> -->
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="桥址处地震烈度：" class="form-item" prop="intensity">
                            <el-select v-model="params.intensity" placeholder="请选择" class="form-select"
                                :disabled="disabled && !!route.query.operateType">
                                <el-option v-for="item in optionList4" :label="item.dictItemName"
                                    :value="item.dictItemCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="场地分类：" class="form-item" prop="siteSoil">
                            <el-select v-model="params.siteSoil" placeholder="请选择" class="form-select"
                                :disabled="disabled && !!route.query.operateType">
                                <el-option v-for="item in optionList3" :label="item.dictItemName"
                                    :value="item.dictItemCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="地基失效(液化、沉陷、滑坡、地裂)程度：" class="form-item" prop="foundationFail">
                            <el-select v-model="params.foundationFail" placeholder="请选择" class="form-select"
                                :disabled="disabled && !!route.query.operateType">
                                <el-option v-for="item in optionList5" :label="item.dictItemName"
                                    :value="item.dictItemCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="上部结构形式：" class="form-item" prop="superStructure">
                            <el-select v-model="params.superStructure" placeholder="请选择" class="form-select"
                                :disabled="disabled && !!route.query.operateType">
                                <el-option v-for="item in optionList6" :label="item.dictItemName"
                                    :value="item.dictItemCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="支座类型：" class="form-item" prop="bearing">
                            <el-select v-model="params.bearing" placeholder="请选择" class="form-select"
                                :disabled="disabled && !!route.query.operateType">
                                <el-option v-for="item in optionList7" :label="item.dictItemName"
                                    :value="item.dictItemCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="墩台高度：" class="form-item" prop="pierHeight">
                            <el-select v-model="params.pierHeight" placeholder="请选择" class="form-select"
                                :disabled="disabled && !!route.query.operateType">
                                <el-option v-for="item in optionList11" :label="item.dictItemName"
                                    :value="item.dictItemCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="墩台类型与材料：" class="form-item" prop="pierMaterial">
                            <el-select v-model="params.pierMaterial" placeholder="请选择" class="form-select"
                                :disabled="disabled && !!route.query.operateType">
                                <el-option v-for="item in optionList9" :label="item.dictItemName"
                                    :value="item.dictItemCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="基础类型：" class="form-item" prop="basement">
                            <el-select v-model="params.basement" placeholder="请选择" class="form-select"
                                :disabled="disabled && !!route.query.operateType">
                                <el-option v-for="item in optionList8" :label="item.dictItemName"
                                    :value="item.dictItemCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="跨长与跨度数目：" class="form-item" prop="number">
                            <el-select v-model="params.number" placeholder="请选择" class="form-select"
                                :disabled="disabled && !!route.query.operateType">
                                <el-option v-for="item in optionList12" :label="item.dictItemName"
                                    :value="item.dictItemCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="设防情况：" class="form-item" prop="fortification">
                            <el-select v-model="params.fortification" placeholder="请选择" class="form-select"
                                :disabled="disabled" clearable>
                                <el-option v-for="item in optionList2" :label="item.dictItemName"
                                    :value="item.dictItemCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="11">
                        <el-form-item label="维护时间:" class="form-item" prop="createTime">
                            <el-date-picker v-model="params.createTime" type="date" placeholder="选择日期" :disabled="disabled">
                            </el-date-picker>
                        </el-form-item>
                    </el-col> -->
                </el-row>
                <!-- <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="维护人所属单位：" class="form-item" prop="orgName">
                            <el-input v-model="params.orgName" placeholder="" :disabled="disabled" clearable />
                        </el-form-item>
                    </el-col>
                </el-row> -->
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="备注：" class="form-item" prop="note">
                            <el-input v-model="params.note" type="textarea" placeholder=""
                                :disabled="disabled && !!route.query.operateType" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <!-- <el-form-item label="维护人：" class="form-item" prop="userName">
                            <el-input v-model="params.userName" placeholder="" :disabled="disabled" clearable />
                        </el-form-item> -->
                    </el-col>
                </el-row>
                <el-row v-if="isAdd" justify="end">
                    <el-form-item class="bottom-button">
                        <el-button type="primary" @click="handleVerify" v-if="!route.query.id">验证</el-button>
                        <el-button type="primary" @click="onCalc" v-if="route.query.id">计算</el-button>
                        <el-button type="primary" @click="onSubmit" v-if="route.query.id">提交</el-button>
                    </el-form-item>
                </el-row>
                <div class="comparison">
                    <el-form-item>
                        <MultilineFormula display="inline-block" font-size="30px" tagOffset="-6px" :option="[
                            { content: 'A', sub: 'i' },
                            { content: '=' },
                            { content: 'W', sub: '0' },
                            { content: '∏', scale: 1.5, topContent: '9', bottomContent: 'j=1', margin: '0 0 0 10px' },
                            { content: '∏', scale: 1.5, topContent: '2或3', bottomContent: 'k=1', margin: '0 0 0 10px' },
                            { content: 'W', sub: 'jk' },
                            { topContent: 'X', },
                            { super: 'jk', }
                        ]">
                        </MultilineFormula>=
                        <el-input placeholder="" v-model="params.calculationResults" readonly clearable
                            style="width:160px;"></el-input>
                    </el-form-item>
                    <el-form-item label="修正值：" label-width="auto">
                        <el-input v-model="params.calculationResultsCorrect" placeholder="请输入"></el-input>
                    </el-form-item>

                    <h4>将计算得到的桥梁震害度与下表统计给出的经验区间比对</h4>
                    <el-table class="listTable" ref="multipleTableRef" border :data="tableData" style="width: 100%"
                        :cell-style="{ border: '1px solid #e5ebf7' }"
                        :header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
                        <el-table-column prop="jbwh" header-align="center" align="center" label="基本完好" />
                        <el-table-column prop="qwph" header-align="center" align="center" label="轻微破坏" />
                        <el-table-column prop="zdph" header-align="center" align="center" label="中等破坏" />
                        <el-table-column prop="yzhh" header-align="center" align="center" label="严重破坏" />
                        <el-table-column prop="hh" header-align="center" align="center" label="毁坏" />
                    </el-table>
                    <div class="seismicDamageGrade">
                        <span>于“年度”建设的“桥梁名称”的震害等级为</span>
                        <el-input v-model="params.damage" readonly clearable
                            style="width: 160px; margin: 0 10px;"></el-input>
                        <span>修正值：</span>
                        <el-input v-model="params.damageCorrect" placeholder="请输入" style="width: 160px;"
                            clearable></el-input>
                    </div>
                </div>
            </el-form>
            <!-- 版本查看 -->
            <GetVersion v-if="openDialog" v-model:open="openDialog" @recalculateVersion="recalculateVersion" type="4" />
            <el-dialog v-model="dialogVisible" @close="cancle" title="提示" width="500px">
                <p v-for="item in messageList">{{ item.label }}
                    <el-popover placement="bottom" title="提示详情" :width="200" trigger="click">
                        <template #reference>
                            <span style="color: #107ce5;cursor: pointer;">提示详情</span>
                        </template>
                        <template #default>
                            <p v-for="val in item.value">{{ val }}</p>
                        </template>
                    </el-popover>
                </p>
                <p>&nbsp;</p>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { reactive, toRefs } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus'
// 接口
import { getInfo } from '@/api/login';
import {
    getByIdAndType, //查询
    cobVulnerability, //计算
    saveVulnerability, //保存
    recalculateCb,//验证
    saveCbResult,//计算并保存
} from "@/api/lifelineVulnerAnalysis/lifelineVulnerAnalysis.js";
import { getValidDictItemsByDictCode } from "@/api/map/disasterDataManagement/lifelineSystemInfo.js";
// 公用方法
import { parseTime } from "@/utils/ruoyi.js";
// 引入公式组件
import Formula from '@/components/Formula';
import MultilineFormula from '@/components/Formula/multiline';
import GetVersion from '../underPipeNet/dataFile/Version.vue';

// 引入store
import useUserStore from '@/store/modules/user';
import useDictStore from '@/store/modules/dict';
// 获取pinia
const userStore = useUserStore();
const dictStore = useDictStore();
// 用户名
const userName = computed(() => userStore.name || '');
// 所属机构名称
const orgName = computed(() => userStore.orgName || '');

// 当前实例
const { proxy } = getCurrentInstance();
// 当前路由
const route = useRoute();
const router = useRouter();

// 是否是新增页，有路由参数是详情页，否则是新增页
let isAdd = computed(() => (route.query.id && route.query.operateType ? false : true));
// 禁用
const disabled = ref(false);
//验证是否yyyy年份（非必填）
const isYearNotMust = (rule, value, callback) => {
    if (value == '' || value == undefined || value == null) {
        callback();
    } else if (isNaN(Number(value))) {
        callback(new Error('请输入yyyy格式如2022'));
    } else if (value.toString().length != 4) {
        callback(new Error('请输入yyyy格式如2022'));
    } else if (value.toString().indexOf(".") != -1) {
        callback(new Error('请输入yyyy格式如2022'));
    } else {
        callback();
    }
}
const data = reactive({
    // 表单参数
    params: {
        name: "",//桥梁名称
        year: "",//年代
        intensity: "",//桥址处地震烈度
        siteSoil: "",//场地分类
        foundationFail: "",//地基失效(液化、沉陷、滑坡、地裂)程度
        superStructure: "",//上部结构形式
        bearing: "",//支座类型
        pierHeight: "",//墩台高度
        pierMaterial: "",//墩台类型与材料
        basement: "",//基础类型：
        number: "",//跨长与跨度数目
        fortification: "", //设防情况
        createTime: parseTime(new Date()), //维护时间
        userName: userName.value, //维护人
        orgName: orgName.value, //维护人所属单位
        note: "",//备注
        calculationResults: "",//计算结果
        calculationResultsCorrect: "",//ai修正值
        damage: "",//结果
        damageCorrect: "",//震害等级修正值
    },
    // 表单验证规则
    rules: {
        name: [
            { required: true, message: '请输入', trigger: 'blur' },
        ],
        year: [{
            required: true,
            message: "请输入正确数值",
            validator: isYearNotMust,
            trigger: ["change", "blur"],
        }],
        intensity: [
            { required: true, message: '请选择', trigger: 'change' }
        ],
        siteSoil: [
            { required: true, message: '请选择', trigger: 'change' }
        ],
        foundationFail: [
            { required: true, message: '请选择', trigger: 'change' }
        ],
        superStructure: [
            { required: true, message: '请选择', trigger: 'change' }
        ],
        bearing: [
            { required: true, message: '请选择', trigger: 'change' }
        ],
        pierHeight: [
            { required: true, message: '请选择', trigger: 'change' }
        ],
        pierMaterial: [
            { required: true, message: '请选择', trigger: 'change' }
        ],
        basement: [
            { required: true, message: '请选择', trigger: 'change' }
        ],
        number: [
            { required: true, message: '请选择', trigger: 'change' }
        ],
        fortification: [
            { required: true, message: '请选择', trigger: 'change' }
        ],
        note: [
            { required: false, message: "请输入", trigger: "blur" },
            { max: 500, message: "最多输入500个字", trigger: ["change", "blur"] },
        ],
    },
    //桥址处地震烈度候选值：Ⅵ、Ⅶ、Ⅷ、Ⅸ、Ⅹ
    rebarTypeOptions: [
        {
            value: 'Ⅵ',
            label: 'Ⅵ'
        }, {
            value: 'Ⅶ',
            label: 'Ⅶ'
        }, {
            value: 'Ⅷ',
            label: 'Ⅷ'
        }, {
            value: 'Ⅸ',
            label: 'Ⅸ'
        }, {
            value: 'Ⅹ',
            label: 'Ⅹ'
        }
    ],
    // 设防情况
    fortificationOptions: dictStore.fortificationOptions || [],
    // 年份
    yearsOptions: dictStore.yearsOptions1 || [],
    //场地分类候选值：I、II、Ⅲ
    siteSoilOptions: [
        {
            value: 'I',
            label: 'I'
        }, {
            value: 'II',
            label: 'II'
        }, {
            value: 'Ⅲ',
            label: 'Ⅲ'
        }
    ],
    //地基失效程度候选值：无、轻、重
    cdOptions: [
        {
            value: '无',
            label: '无'
        }, {
            value: '轻',
            label: '轻'
        }, {
            value: '重',
            label: '重'
        }
    ],
    //候选值：连续梁、刚架板梁、拱简支梁、悬臂梁
    superStructureOptions: [
        {
            value: '刚架、单拱',
            label: '刚架、单拱'
        }, {
            value: '连续梁、板梁、连孔拱',
            label: '连续梁、板梁、连孔拱'
        }, {
            value: '简支梁、悬臂梁',
            label: '简支梁、悬臂梁'
        }
    ],
    //候选值：有防落梁措施 橡胶支座 一般支座
    bearingOptions: [
        {
            value: '有防落梁措施',
            label: '有防落梁措施'
        }, {
            value: '橡胶支座',
            label: '橡胶支座'
        }, {
            value: '一般支座',
            label: '一般支座'
        }
    ],
    //候选值：<5米、5米—10米、>10米
    pierHeightOptions: [
        {
            value: '<5米',
            label: '<5米'
        }, {
            value: '5米—10米',
            label: '5米—10米'
        }, {
            value: '>10米',
            label: '>10米'
        }
    ],
    //候选值：钢筋混凝土、砖石
    pierMaterialOptions: [
        {
            value: '钢筋混凝土',
            label: '钢筋混凝土'
        }, {
            value: '砖石',
            label: '砖石'
        }
    ],
    //候选值：扩大基础-桩柱基础 排架桩-高桩承台
    basementOptions: [
        {
            value: '扩大基础、桩柱基础',
            label: '扩大基础、桩柱基础'
        }, {
            value: '排架桩、高桩承台',
            label: '排架桩、高桩承台'
        }
    ],
    //候选值：孔数≤3，跨长≤10米、孔数>3，跨长>10米
    lengthOptions: [
        {
            value: '孔数≤3，跨长≤10米',
            label: '孔数≤3，跨长≤10米'
        }, {
            value: '孔数>3，跨长>10米',
            label: '孔数>3，跨长>10米'
        }
    ],
});
const {
    params,
    rules,
    rebarTypeOptions,
    fortificationOptions,
    yearsOptions,
    siteSoilOptions,
    cdOptions,
    superStructureOptions,
    bearingOptions,
    pierHeightOptions,
    pierMaterialOptions,
    basementOptions,
    lengthOptions,
} = toRefs(data);

// 表格
const tableData = [
    {
        jbwh: '0---1.23',
        qwph: '1.23--2.20',
        zdph: '2.20--3.38',
        yzhh: '3.38--4.40',
        hh: '>4.40',
    }
];

// 获取用户
function getUserInfo(userId) {
    getInfo(userId).then(response => {
        const { code, user } = response;
        if (user) {
            params.value.userName = user.userName;
            params.value.orgName = user.orgName;
        }
    });
};

//桥梁易损性计算
const onCalc = () => {
    proxy.$refs['queryRef'].validate(async (valid, fields) => {
        if (valid) {
            let query = {
                ...params.value,
                bridgeType:route.query.bridgeType,
                // "W0": "0.85", // 可不传，后端计算用
            };
            proxy.$modal.loading('正在努力计算,请耐心等待！');
            cobVulnerability(query).then((res) => {
                proxy.$modal.closeLoading();
                const { code, data } = res;
                if (code === 200 && data) {
                    proxy.$modal.msgSuccess('计算完成！计算结果未保存，若需保存结果，请计算后点击提交按钮！');
                    // params.value = data;
                } else {
                    proxy.$modal.msgWarning("计算失败!");
                }
            }).catch(err => {
                proxy.$modal.closeLoading();
                console.log(err.message);
            });
        } else {
            proxy.$refs['queryRef'].scrollToField(Object.keys(fields)[0])
        }
    })
};

//桥梁易损性保存
const onSubmit = () => {
    proxy.$refs['queryRef'].validate((valid, fields) => {
        if (valid) {
            proxy.$modal.loading('正在保存,请耐心等待！');
            const query = {
                type:'4',
                bridgeType:route.query.bridgeType,
                bridgeParam:{...params.value}
            }
            saveVulnerability(query).then((res) => {
                proxy.$modal.closeLoading();
                const { code } = res;
                if (code === 200) {
                    proxy.$modal.msgSuccess("保存成功！");
                    // 延迟跳转
                    setTimeout(() => {
                        router.push('/lifelineVulnerAnalysis/lifelineMain')
                    }, 1500)
                } else {
                    proxy.$modal.msgWarning("保存失败!");
                }
            }).catch(err => {
                proxy.$modal.closeLoading();
                console.log(err.message);
            });
        } else {
            proxy.$refs['queryRef'].scrollToField(Object.keys(fields)[0])
        }
    })
}

// 显示弹框
const openDialog = ref(false)
const handleVerify = () => {
    openDialog.value = true;
}
// 验证
const messageList = ref([]);
const dialogVisible = ref(false);
const cancle = () => {
    dialogVisible.value = false;
}
const recalculateVersion = (version) => {
    console.log(version,'llal');
    openDialog.value = false;
    recalculateCb({ versionId:version.id, type: '4',bridgeType:version.bridgeType }).then(res => {
        if (JSON.stringify(res.data) == '{}') {
            ElMessageBox.confirm(
                '数据通过验证，是否计算？', '提示',
                {
                    confirmButtonText: '计算并保存',
                    cancelButtonText: '取消',
                    type: 'success',
                }
            )
                .then(() => {
                    saveCbResult({ versionId:version.id,bridgeType:version.bridgeType }).then(response => {
                        if (response.code == 200) {
                            router.push(`/lifelineVulnerAnalysis/lifelineMain?type=4`)
                        }
                    })
                }).catch(() => { })
        } else {
            const { data } = res;
            messageList.value = [];
            for (let i in data) {
                messageList.value.push({ label: `第${i}行计算参数未填写完整，请补充完整再计算。`, value: data[i] })
            }
            dialogVisible.value = true;
        }
    })
}

// 获取数据
function getData(query) {
    getByIdAndType(query).then((res) => {
        const { code, data } = res;
        if (code === 200 && data) {
            const { bridgeVo, tableEntity } = data;
            if (bridgeVo) {
                params.value = { ...bridgeVo };
                params.value.fortification = tableEntity.fortification;
                const dateTime = new Date()
                params.value.createTime = parseTime(dateTime);
                // 根据id获取用户信息
                params.value.userName = userStore.name;
                params.value.orgName = userStore.orgName;
            }
        }
    }).catch(err => {
        console.log(err.message);
    });
}

//字典表查询
const optionList1 = ref([])
const optionList2 = ref([])
const optionList3 = ref([])
const optionList4 = ref([])
const optionList5 = ref([])
const optionList6 = ref([])
const optionList7 = ref([])
const optionList8 = ref([])
const optionList9 = ref([])
const optionList10 = ref([])
const optionList11 = ref([])
const optionList12 = ref([])
/** 获取字典值 */
async function getDictData() {
    await getValidDictItemsByDictCode("smxjsnd").then(response => {
        optionList1.value = response.data;//建造年代
    });
    await getValidDictItemsByDictCode("smxsfqk").then(response => {
        optionList2.value = response.data;//设防情况
    });
    await getValidDictItemsByDictCode("smxqlcdtfl").then(response => {
        optionList3.value = response.data;//场地分类
    });
    await getValidDictItemsByDictCode("smxsfld").then(response => {
        optionList4.value = response.data;//桥址处地震烈度
    });
    await getValidDictItemsByDictCode("smxqldjsx").then(response => {
        optionList5.value = response.data;//地基失效程度
    });
    await getValidDictItemsByDictCode("smxqlsbjg").then(response => {
        optionList6.value = response.data;//上部结构
    });
    await getValidDictItemsByDictCode("smxqlzzxs").then(response => {
        optionList7.value = response.data;//支座形式
    });
    await getValidDictItemsByDictCode("smxqljcxs").then(response => {
        optionList8.value = response.data;//基础型式
    });
    await getValidDictItemsByDictCode("smxqlqdcl").then(response => {
        optionList9.value = response.data;//桥墩材料/桥台材料
    });
    await getValidDictItemsByDictCode("smxqlqtlx").then(response => {
        optionList10.value = response.data;//桥台类型
    });
    await getValidDictItemsByDictCode("smxqldtgd").then(response => {
        optionList11.value = response.data;//桥墩高度
    });
    await getValidDictItemsByDictCode("smxqlkcykd").then(response => {
        optionList12.value = response.data;//跨长与跨度数目
    });
}

getDictData();

// 挂载
onMounted(() => {
    const id = route.query.id;
    if (id) {
        disabled.value = true;
        // 获取数据
        getData({ id, type: 4 ,bridgeType:route.query.bridgeType});
    } else {
        disabled.value = false;
    }
});
</script>

<style lang="scss">
.table-wrapper {
    position: relative;

    h4 {
        font-size: 16px;
        font-weight: bold;
        color: #107ce5;
        text-align: center;
    }

    .comparison {
        h4 {
            text-align: left;
        }

        .seismicDamageGrade {
            margin: 10px 0;
        }
    }

}</style>


